#########################################
# Set up and common commands & packages #
#########################################

# Checks that relevant packages (**not** imports!) are available and if so loads them in the workspace
if (!isTRUE(requireNamespace("icons", quietly = TRUE))) {
  stop("You need to install the packages 'icons'. Please run in your R terminal:\n devtools::install_github('ropenscilabs/icons')")
}
# If INLA is installed but not loaded then attach the Namespace (so that all the relevant functions are available)
if (isTRUE(requireNamespace("icons", quietly = TRUE))) {
  if (!is.element("icons", (.packages()))) {
    attachNamespace("icons")
  }
}

# Support Chinese
Sys.setlocale(category = "LC_CTYPE", locale = "chs")

# Sets default fonts for tikz
library(tikzDevice)
options(tikzLatexPackages=c(getOption("tikzLatexPackages"),"\\usepackage{inconsolata}","\\usepackage{bm}",
                            "\\usepackage[scaled=.89]{helvet}\n\\renewcommand{\\familydefault}{\\sfdefault}\n"))

# Trick to automatically convert pdf graphs generated with dev='tikz' into png so they work in html format
# see: https://github.com/rstudio/bookdown/issues/275
# NB: Need to specify 'density=600' in 'image_read' to get same quality as tikz
knitr::opts_hooks$set(dev = function(options) {
  if (identical(options$dev, 'tikz') && !knitr:::is_latex_output()) {
    options$fig.process = function(x) {
      if (!grepl('[.]pdf$', x)) return(x)
      x2 = sub('pdf$', 'png', x)
      magick::image_write(magick::image_read(x,density=600), x2, format = 'png', quality=90, density=600)
      x2
    }
  }
  options
})

# This is a hack to insert 'alt-text' in images created by the R chunks
# source: https://ropensci.org/technotes/2020/04/23/rmd-learnings/
# NB: the 'alt-text' needs to be **'title'** attribute that gets included in the list 'opts'
# which is included as part of the set up in the chunk, for example
#    ```{r echo=FALSE,opts=list(title="Alt-text",width="45%"...)}
# (see: https://www.computerhope.com/issues/ch001076.htm).
# Also, needs to specify the 'width' option (= what would normally be 'out.width') to ensure
# that the resulting HTML code to format the graph
knitr::knit_hooks$set(
  plot = function(x, options) {
    opts <- options$opts
    paste0(
      "<img src=",
      '"', x, '" ',
      if (!is.null(opts)) {
        # Here include the styling for the graphs - this ensure it's centered
        paste('style="display: block; margin: auto;"',
              # And this "glues" the options passed by the user (including the 'alt-text')
              glue::glue_collapse(glue::glue('{names(opts)}="{opts}"'),sep = " ")
        )
      },
      ">\n"
    )
  },
  # This sets up a switch that allows to automatically crop the images generated by R
  # https://bookdown.org/yihui/rmarkdown-cookbook/crop-plot.html
  knitr::knit_hooks$set(crop = knitr::hook_pdfcrop)
)

# Defaults for figure size
# fig.retina=3 improves the quality of the resulting graph (https://arm.rbind.io/slides/xaringan.html#89)
knitr::opts_chunk$set(fig.width=10, fig.height=9, out.width="55%", fig.align='center', fig.retina=3, crop=TRUE,
                      comment=NA,message=FALSE,error=FALSE)



# This sets up the figure path so that all the R-generated images are stored under 'img'
knitr::opts_chunk$set(fig.path="./img/")


# Table/knitr-related options
library(knitr)
library(kableExtra)
options(htmltools.dir.version = FALSE)
options(knitr.table.format = "html")
knitr::opts_chunk$set(warning = FALSE, message = FALSE)

# This defines how the code is formatted
knitr::opts_chunk$set(
  prompt = TRUE,
  highlight = TRUE,
  #background = '#FFFFFF',
  concordance=TRUE
)


# Spacing - uses R to create HTML code to make space
vspace=function(space="-20px") {
  paste('<span style="display:block; margin-top:',space,';"></span>')
}
# This creates a 'tab' function that adds horizontal space(s) --- default is 1 but can add as many as you like
tab=function(x=1) {
  cat(rep("&nbsp;",3),sep="")
}


# LaTeX maths & colors:
# Defines a LaTeX macro to typeset text using the default font (as for the rest of the text in the slides)
sftext=function(x) {
  paste0("\\style{font-family:inherit;}{\\text{",x,"}}")
}
# can use xaringan colors for equations, eg '.red[$$x^2$$]'
# if a color is not named (but defined in the .css file), need to use the MathJax command '\class', eg '$\class{color}{x^2}$'


# Macro to include figures from file
# NB: It assumes by default that the images to be loaded are in the 'img' folder under the current directory
#     ie where the current Rmd presentation is stored. But a full directory can be passed on in the argument 'dir'
include_fig=function(img,dir="./img",width="100%",title="INCLUDE TEXT HERE") {
  filename=file.path(dir,img)
  paste0("<center><img src=",filename," width='",width,"' title='",title,"'></center>")
}

# Creates HTML code to include the samptux icon + link to www.statistica.it/gianluca
# samptux=function(path="assets/logo.png",width="2.0%",text="") {
#   paste0('<span><a href="http://www.statistica.it/gianluca/"><img src="',path,'" title="Go home" width="',width,'"></a>',text,'</span>')
#   # But could use other links/icons, eg
#   #<p><a href="http://www.statistica.it/gianluca/"><i class="fas fa-home" title="Go home" style="color: #bcc0c4;"></i></a></p>
#   # Also, could use the 'xaringanExtra::use_logo()' function as well (which does pretty much the same thing...)
# }

# Adds icons & links on the bottom navbar (in the dedicated 'footer-social' container)
# add_twitter=function() {
#   paste0('&nbsp;<a href="https://twitter.com/giabaio"; title="Follow me on Twitter">',icon::icon_style(icon::fontawesome("twitter"),scale=.8,fill="#bcc0c4",bottom="1em"),'</a>&nbsp;')
# }
# add_email=function() {
#   paste0('&nbsp;<a href="mailto:g.baio@ucl.ac.uk"; title="Email me">',icon::icon_style(icon::fontawesome("envelope",style = "solid"),scale=.8,fill="#bcc0c4"),'</a>&nbsp;')
# }
# add_website=function() {
#   paste0('&nbsp;<a href="http://www.statistica.it/gianluca"; title="Visit my website">',icon::icon_style(icon::fontawesome("firefox"),scale=.8,fill="#bcc0c4"),'</a>&nbsp;')
# }
# 
# twitter=function(alt="") {
#   icon="assets/images/twitter.png"
#   link="https://twitter.com/gianlubaio"
#   htmltools::tags$a(.noWS = c("after-begin", "before-end"),
#                     href = link,
#                     htmltools::tags$img(src = icon, alt = alt, width = "32", height = "32", style = "border: none;")
#   )
# }
# linkedin=function(alt="") {
#   icon="images/linkedin.png"
#   link="https://www.linkedin.com/in/gianluca-baio-b893879/"
#   htmltools::tags$a(.noWS = c("after-begin", "before-end"),
#                     href = link,
#                     htmltools::tags$img(src = icon, alt = alt, width = "32", height = "32", style = "border: none;")
#   )
# }
# github=function(alt="") {
#   icon="images/github.png"
#   link="https://www.github.com/giabaio"
#   htmltools::tags$a(.noWS = c("after-begin", "before-end"),
#                     href = link,
#                     htmltools::tags$img(src = icon, alt = alt, width = "32", height = "32", style = "border: none;")
#   )
# }
# scholar=function(alt="") {
#   icon="images/scholar.png"
#   link="https://scholar.google.com/citations?user=ro0QvGsAAAAJ&hl=en"
#   htmltools::tags$a(.noWS = c("after-begin", "before-end"),
#                     href = link,
#                     htmltools::tags$img(src = icon, alt = alt, width = "32", height = "32", style = "border: none;")
#   )
# }
# researchgate=function(alt="") {
#   icon="images/researchgate.png"
#   link="https://www.researchgate.net/profile/Gianluca_Baio"
#   htmltools::tags$a(.noWS = c("after-begin", "before-end"),
#                     href = link,
#                     htmltools::tags$img(src = icon, alt = alt, width = "32", height = "32", style = "border: none;")
#   )
# }

# Relevant packages (to load globally - not for a single slide)
library(dplyr)
library(ggplot2)
library(xaringanExtra)

# Citations & Bibliography (https://github.com/yihui/xaringan/wiki/Bibliography-and-citations)
# RefManageR: https://arxiv.org/pdf/1403.2036v1.pdf
library(RefManageR)
BibOptions(check.entries = FALSE,
           bib.style = "authoryear",
           style = "markdown",
           cite.style = "authoryear",
           super = FALSE,
           hyperlink = FALSE,
           dashed = FALSE
#           bibpunct = c("(",")","(",")",";",","),
)


# Formats the date in the title-slide
# If the date is specified as a string (to a specific value), then used that, else use current date
if(!is.null(rmarkdown::metadata$date)){date=rmarkdown::metadata$date} else {date=format(Sys.Date(),"%e %B %Y")}

# Also creates a variable 'short_date' that can be used in the footers
short_date=format(as.Date(date,format="%e %b %Y"),"%e %b %Y")

